package com.rui.forkjion;

import java.util.concurrent.RecursiveTask;

/**
 * 求和计算
 */
public class ForkJionDemo extends RecursiveTask<Long> {

    private Long start;

    private Long end;

    private Long temp = 10000L;

    public ForkJionDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if((start - end) >= temp){
            //分支合并计算

            //中间值
            Long mid = (start + end) / 2;

            ForkJionDemo task1 = new ForkJionDemo(start, mid);
            ForkJionDemo task2 = new ForkJionDemo(mid + 1, end);

            task1.fork();
            task2.fork();

            return task1.join() + task2.join();
        }else {
            Long sum = 0L;

            for (Long i = start; i <= end; i++) {
                sum += i;
            }

            return sum;
        }
    }
}
